<template>
  <div class="header-container">
    <div class="header-inner">
      <div class="header-left">
        <div class="logo"></div>
      </div>
      <div class="header-right">
        <a @click="$router.push('/')">首页</a>
        <a v-if="!getUser" @click="$router.push('/login')">登录</a>
        <span v-else class="user-greet">
          <a>{{ getUser.phone }}</a>
          <a class="add-new" @click="$router.push('/newTopic')">发布主题</a>
          <a class="logout" @click="logout">退出</a>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { logout } from '@/api'
import { Toast } from '@/components/Toast'
export default {
  name: 'Header',
  data() {
    return {}
  },

  computed: {
    ...mapGetters({
      getUser: 'user/getUser'
    })
  },

  mounted() {
    const user = sessionStorage.getItem('user')
    console.log('header', JSON.parse(user))
    if (user) {
      this.changeUser(JSON.parse(user))
    }
  },

  methods: {
    ...mapActions({
      changeUser: 'user/changeUser'
    }),

    async logout() {
      const res = await logout()
      if (res.code === 200) {
        sessionStorage.removeItem('user')
        this.changeUser(null)
        Toast({
          type: 'success',
          text: '退出成功'
        })
        window.location.reload()
      }
    }
  }
}
</script>

<style scoped>
.header-container {
  height: 44px;
  background-color: #fff;
  border-bottom: 1px solid rgba(0, 0, 0, 0.22);
}
.header-inner {
  display: flex;
  justify-content: space-between;
  max-width: 980px;
  height: 100%;
  margin: 0 auto;
}
.logo {
  height: 44px;
  width: 120px;
  background: transparent url(~@/assets/img/logo.png) no-repeat center 100% /
    100%;
}
.header-right {
  display: flex;
  align-content: center;
}
.header-right > a {
  margin-left: 8px;
  color: #556;
  line-height: 43px;
  font-size: 15px;
  cursor: pointer;
}
.add-new {
  margin-left: 10px;
  color: #409eff !important;
  font-size: 15px;
  cursor: pointer;
}
.user-greet {
  display: flex;
  align-items: center;
  height: 100%;
  margin-left: 10px;
}
.user-greet > a {
  color: #556;
}
.user-greet > .logout {
  margin-left: 10px;
  color: palevioletred;
  font-size: 15px;
  cursor: pointer;
}
</style>
